<template>
  <!-- 页面总容器：对应用户页的.user-page-container，统一页面背景 -->
  <div class="dept-page-container">
    <!-- 搜索栏卡片：独立卡片，对应用户页的搜索-card -->
    <ContentWrap class="search-card">
      <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input
              v-model="queryParams.name"
              placeholder="请输入部门名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="部门编码" prop="orgCode">
          <el-input
              v-model="queryParams.orgCode"
              placeholder="请输入部门编码"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
          <el-button
              type="danger"
              plain
              @click="toggleExpandAll"
              class="ml-2"
          >
            <Icon icon="ep:sort" class="mr-5px" /> {{ isExpandAll ? '折叠全部' : '展开全部' }}
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表栏卡片：独立卡片，对应用户页的list-card，修复双重边框 -->
    <ContentWrap class="list-card">
      <el-table
          v-loading="loading"
          :data="list"
          row-key="orgCode"
          :default-expand-all="isExpandAll"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          v-if="refreshTable"
          :show-overflow-tooltip="true"
          class="dept-table"
      >
      <el-table-column label="部门名称" align="center" min-width="180" prop="name" />
      <el-table-column label="部门编码" align="center" prop="orgCode" width="140" />
      <el-table-column label="部门简称" align="center" prop="shortName" width="140" />
      <el-table-column label="上级编码" align="center" prop="parentCode" width="140" />
      <el-table-column label="层级路径" align="center" prop="parents" min-width="200" />
      <el-table-column label="创建人" align="center" prop="createUser" width="140" />
      <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="180"
          :formatter="dateFormatter"
      />
      </el-table>

    </ContentWrap>

    <!-- 表单弹窗：保持原有 -->
    <DeptForm ref="formRef" @success="getList" />
  </div>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { handleTree } from '@/utils/tree'
import { DeptApi, Dept } from '@/api/portal/dept'
import { useMessage } from '@/hooks/web/useMessage'
import { useI18n } from 'vue-i18n'
import { onMounted, ref, reactive, nextTick, type Ref } from 'vue'

defineOptions({ name: 'PortalDept' })

// 工具实例
const message = useMessage()
const { t } = useI18n()

// 树形类型定义：保留表格自带树形所需字段
interface DeptTree extends Dept {
  children?: DeptTree[]
  hasChildren?: boolean
}

// 状态变量：保持原有逻辑
const loading: Ref<boolean> = ref(true)
const list: Ref<DeptTree[]> = ref([])
const total: Ref<number> = ref(0)
const isExpandAll: Ref<boolean> = ref(true)
const refreshTable: Ref<boolean> = ref(true)

// 搜索参数：保持原有
const queryParams = reactive({
  name: undefined,
  orgCode: undefined,
  parentCode: undefined,
})

// 表单引用：保持原有
const queryFormRef: Ref<any> = ref(null)
const formRef: Ref<{ open: (type: 'create' | 'update', id?: string) => void } | null> = ref(null)

/** 全部展开/折叠逻辑：保持原有 */
const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 查询部门列表：保持原有 */
const getList = async () => {
  loading.value = true
  try {
    const response = await DeptApi.getDeptPage(queryParams)
    const deptList: Dept[] = response || []
    total.value = response || 0

    const treeData: DeptTree[] = handleTree(
        deptList,
        'orgCode',
        'parentCode',
        'children',
        '-'
    ).map(node => ({
      ...node,
      hasChildren: !!node.children && node.children.length > 0
    }))

    list.value = treeData
  } catch (error: any) {
    console.error('获取部门列表失败:', error)
    message.error(error.message || t('common.fetchFail'))
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

/** 搜索/重置/打开表单：保持原有逻辑 */
const handleQuery = () => {
  getList()
}
const resetQuery = () => {
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  queryParams.name = undefined
  queryParams.orgCode = undefined
  queryParams.parentCode = undefined
  getList()
}
const openForm = (type: 'create' | 'update', orgCode?: string) => {
  formRef.value?.open(type, orgCode)
}

// 初始化加载列表
onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
// 1. 页面总容器：完全对齐用户页的.user-page-container
.dept-page-container {
  padding: 16px;
  background-color: #f5f7fa; // 统一页面背景色，突出卡片
  min-height: calc(100vh - 120px); // 确保页面高度足够
}

// 2. 搜索栏卡片：对齐用户页的.search-card
.search-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 16px;
  margin-bottom: 16px; // 与列表卡片保持间距
}

// 3. 列表栏卡片：对齐用户页的.list-card，修复双重边框
.list-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  padding: 16px;
  overflow: hidden; // 避免内部元素溢出
}

// 4. 表格样式：清除自带边框，解决双重边框问题（核心修复点）
.dept-table {
  border: none !important; // 清除表格外边框，依赖外层list-card边框
  margin-bottom: 16px; // 与分页保持间距

  // 仅保留表格内部单元格边框，对齐用户页表格样式
  th, td {
    border-color: #f1f5f9 !important;
  }

  // 优化树形表格的展开图标样式（可选，保持美观）
  .el-table__expand-icon {
    color: #94a3b8;
  }
}

// 5. 分页容器：完全对齐用户页的分页布局（移入列表卡片内，右对齐）
.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 8px;
}

// 6. 响应式适配：对齐用户页的适配逻辑
@media (max-width: 1200px) {
  .dept-page-container {
    padding: 12px;
  }
  .search-card, .list-card {
    padding: 12px;
  }
  .dept-table {
    th, td {
      font-size: 13px;
    }
  }
}

@media (max-width: 992px) {
  .dept-table .el-table-column {
    font-size: 12px;
  }
}
</style>
